import store from '@/store';
import router from '@/router';
import nprogress from 'nprogress';
import { getToken } from '@/utils/cookie';
import getPageTitle from '@/utils/get-page-title';
import { Message } from 'element-ui';
import { asyncRoutes } from '@/router/asyncRoutes';

const whiteList = ['/login', '/404'];

const getFirseRoutesPermission = (permissions) => {
  const firseRoutesPermission = permissions.map(item => {
    return item.split(':')[0];
  });
  return Array.from(new Set(firseRoutesPermission));
};

const getSecondRoutesPermission = (permissions) => {
  const secondRoutesPermission = permissions.map(item => {
    return `${item.split(':')[0]}:${item.split(':')[1]}`;
  });

  return Array.from(new Set(secondRoutesPermission));
};

const getButtonsPermission = (permissions) => {
  const buttonsPermission = Array.from(new Set(permissions.map(item => `${item.split(':')[0]}:${item.split(':')[1]}:${item.split(':')[2]}`)));
  store.commit('menusStore/updateButtons', buttonsPermission);
};

router.beforeEach(async(to, from, next) => {
  nprogress.start();
  const token = getToken();
  if (token) {
    if (to.path === '/login') {
      next(false);
      nprogress.done();
      Message.warning('已经登录');
    } else {
      if (store.getters.name) {
        next();
      } else {
        try {
          const { menus, permissions } = await store.dispatch('userStore/fetchUserInfo');
          const firseRoutesPermission = getFirseRoutesPermission(permissions);
          const secondRoutesPermission = getSecondRoutesPermission(permissions);
          getButtonsPermission(permissions);
          const resultRoutes = await store.dispatch('menusStore/getRoutes', { firseRoutesPermission, secondRoutesPermission });
          router.addRoutes([...resultRoutes]);
          next({ ...to, replace: true });
        } catch (error) {
          console.log(error);
          router.push({ path: '/login', query: { redirect: to.fullPath } });
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next({
        path: '/login',
        query: {
          return_url: to.fullPath,
        },
      });
      nprogress.done();
      Message.warning('请先登录');
    }
  }
});

router.afterEach((to, from) => {
  nprogress.done();
  document.title = getPageTitle(to.meta.title);
});
